package com.sxkf.template.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sxkf.core.api.vo.R;
import com.sxkf.template.entity.SpellOut;
import com.sxkf.template.entity.User;
import com.sxkf.template.service.SpellOutService;
import com.sxkf.template.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 商品拼团 前端控制器
 * </p>
 *
 * @author 杨玉龙
 * @since 2024-12-02 18:10:34
 */
@Api(tags = "商品拼团模块")
@RestController
@RequestMapping("/spellOut")
public class SpellOutController {
    @Resource
    private SpellOutService spellOutService;
    @Resource
    private UserService userService;

    @ApiOperation(value = "查询商品拼团信息")
    @GetMapping(value = "/list")
    public R<?> list(@RequestParam String productId){
        List<SpellOut> list = spellOutService.list(new LambdaQueryWrapper<SpellOut>()
                .eq(SpellOut::getState,"0")
                .eq(SpellOut::getProductId, productId));
        list.forEach(item->{
            User user = userService.getById(item.getCreateId());
            item.setPhone(user.getPhone());
            item.setAvatar(user.getAvatar());
            item.setLeaveCount(item.getNeedCount() - item.getJoinCount());
            Date createTime = item.getCreateTime();
            Date endTime = item.getEndTime();
            item.setLastTime(endTime.getTime() - createTime.getTime());
        });
        return R.success(list);
    }

    @ApiOperation(value = "开团")
    @PostMapping(value = "/create")
    public R<?> create(@RequestBody SpellOut spellOut){
        spellOutService.create(spellOut);
        return R.success();
    }

    @ApiOperation(value = "参与拼团")
    @PostMapping(value = "/join")
    public R<?> join(@RequestParam String id,@RequestParam String userId){
        spellOutService.join(id,userId);
        return R.success();
    }


    @ApiOperation(value = "我的拼团信息")
    @GetMapping(value = "/mySpellOutPage")
    public R<IPage<SpellOut>> mySpellOutPage(@RequestParam Integer pageNo,
                                             @RequestParam Integer pageSize,
                                             @RequestParam String userId){

        Page<SpellOut> page = spellOutService.page(new Page<>(pageNo, pageSize), new LambdaQueryWrapper<SpellOut>()
                .like(SpellOut::getJoinUserList, userId));

        page.getRecords().forEach(item-> {
            User user = userService.getById(item.getCreateId());
            item.setPhone(user.getPhone());
            item.setAvatar(user.getAvatar());
        });

        return R.success(page);
    }


}
